<template>
  <div>
    <!-- 商品分类参数组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意，只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
      <!-- 级联选择器 -->
      <!-- options指定数据源 selectedKeys选中父级id与v-model绑定在一起 -->
      <el-row>
        <el-col>
          <span>请选择商品分类：</span>
          <el-cascader
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parentCateChanged"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addParamsBtn">添加参数</el-button>
          <!-- 渲染动态参数列表 -->
          <el-table :data="manyTabData" border>
            <el-table-column type="expand">
              <!-- 参数属性 -->
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加、删除参数属性 -->
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  style="width:80px"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsBtn(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamsBtn(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="添加静态属性" name="only">
          <el-button type="success" :disabled="isBtnDisabled" @click="addParamsBtn">静态属性</el-button>
          <!-- 渲染静态属性列表 -->
          <el-table :data="onlyTabData" border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="i"
                  v-for="(item,i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i,scope.row)"
                >{{item}}</el-tag>
                <!-- 添加、删除参数属性 -->
                <!-- 输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  style="width:80px"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <!-- 按钮 -->
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsBtn(scope.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamsBtn(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加Dialog框，公用一个 -->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addDialog"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
      >
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑Dialog框，静态，动态公用一个 -->
    <el-dialog
      :title="'编辑'+titleText"
      :visible.sync="editDialog"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsRules"
        ref="editParamsRef"
        label-width="100px"
      >
        <el-form-item label="属性名称" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 分类列表
      cateList: [],
      // 指定级联选择器配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 选中的父级分类的id数组，与v-model一起绑定
      selectedKeys: [],
      // 被激活的页签的名称，only是获取静态参数，many是获取动态属性
      activeName: 'many',
      // 动态参数的数据
      manyTabData: [],
      // 静态属性的数据
      onlyTabData: [],
      // dialog弹框
      addDialog: false,
      editDialog: false,
      addParamsForm: {
        attr_name: ''
      },
      editParamsForm: {
        attr_name: ''
      },
      // 添加参数验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入属性名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      }
      // // 文本框显示或隐藏
      // inputVisible: false
      // // 文本框的值
      // inputValue: ''
    }
  },
  created() {
    this.getCateList()
  },
  // 计算属性
  computed: {
    isBtnDisabled() {
      // 没有选中三级分类则禁用
      if (this.selectedKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 计算当前选中分类的id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    // 计算当前是动态参数还是静态属性only
    titleText() {
      if (this.activeName === 'many') {
        return '动态属性'
      }
      return '静态属性'
    }
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      // res.data.result 才是当前商品分类的数据
      this.cateList = res.data
      // console.log(res)
    },
    // 级联选择器发生改变
    parentCateChanged() {
      // console.log(this.selectedKeys)
      this.getParamsList()
      // 如果选择的不是三级列表，就将当前数据清空
      if (this.selectedKeys.length !== 3) {
        this.manyTabData = []
        this.onlyTabData = []
        this.selectedKeys = []
      }
    },
    // tabs标签页点击事件处理函数
    handleTabClick() {
      // console.log(this.activeName)
      this.getParamsList()
    },

    // 获取params数据
    async getParamsList() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败')
      }
      // 展示动静态参数的可选项
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加一个布尔值来控制文本框的显示或隐藏
        item.inputVisible = false
        // 添加一个inputValue来保存文本框的值
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTabData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTabData = res.data
      }
      // console.log(res.data)
    },
    // 添加静态属性和动态参数弹框
    addParamsBtn() {
      this.addDialog = true
    },
    // 添加参数成功，提交
    addParams() {
      this.$refs.addParamsRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('添加参数规则不正确')
        }
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getParamsList()
        this.addDialog = false
        // console.log(res)
      })
    },
    // 重置
    addDialogClosed() {
      this.$refs.addParamsRef.resetFields()
    },
    // 修改参数
    async editParamsBtn(attrId) {
      // console.log(attrId)
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attrId}`,
        {
          params: { attr_sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取当前参数失败')
      }
      this.editParamsForm = res.data
      // console.log(res)

      this.editDialog = true
    },
    // 修改参数提交
    editParams() {
      this.$refs.editParamsRef.validate(async valid => {
        // console.log(valid)
        if (!valid) {
          return this.$message.error('修改失败')
        }
        // this.$message.success('修改成功')
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          }
        )
        // console.log(res)

        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('修改成功')
        this.getParamsList()
        this.editDialog = false
      })
    },
    // 重置
    editDialogClosed() {
      this.$refs.editParamsRef.resetFields()
    },
    // 删除动态参数和静态属性操作操作
    async delParamsBtn(attrId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该角色，是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => {
        return err
      })
      // 如果用户确认了删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('不要慌，还没有删除')
      }
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attrId}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除用户成功')
      this.getParamsList()
    },
    // 添加参数 newTag事件
    handleInputConfirm(row) {
      // console.log('ok123')
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 如果用户输入了合法的数据就将他保存起来
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 点击按钮的时候，文本框显示，可以编辑操作
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 如果用户输入了合法的数据就将其保存起来
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('修改或删除参数项成功')
      console.log(res)
    },
    // 删除参数，属性下的对应可选项
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
